import { debounce } from '@neu/biz-core/utils'
import {
  getPieOption,
  getBarOption,
  getBarOption as getLineOption,
  getGaugeOption,
  getRadarOption,
  getDoughnutOption,
  getSimpleBarOption
} from '../options'

const chartOptions = {
  getPieOption,
  getBarOption,
  getLineOption,
  getGaugeOption,
  getRadarOption,
  getDoughnutOption,
  getSimpleBarOption
}

export default {
  data() {
    return {
      $_sidebarElm: null,
      $_resizeHandler: null
    }
  },
  mounted() {
    this.$$chartInstance = null
    this.initChart(this.id)
  },
  activated() {
    if (!this.$_resizeHandler) {
      // avoid duplication init
      this.initListener()
    }
    // when keep-alive chart activated, auto resize
    this.resize()
  },
  beforeDestroy() {
    this.$$chartInstance.dispose()
    this.$$chartInstance = null
    this.destroyListener()
  },
  deactivated() {
    this.destroyListener()
  },
  methods: {
    // 同时还接受父组件传来的 option
    setOption(option) {
      this.$$chartInstance && this.$$chartInstance.setOption(option)
    },
    setDataSource() {
      const option = this.$$chartInstance.getOption()
      option.dataset.source = this.dataSource
      this.setOption(option)
    },
    initChart(id) {
      const chartDom = document.getElementById(id)
      this.$$chartInstance = this.$echarts.init(chartDom, 'echartsTheme')
      const type = this.type
      const option = chartOptions[`get${type}Option`](this.title, this.dataSource, type.toLowerCase())
      this.setOption(option)
      this.initListener()
    },
    initListener() {
      this.$_resizeHandler = debounce(() => {
        this.resize()
      }, 100)
      window.addEventListener('resize', this.$_resizeHandler)

      this.$_sidebarElm = document.getElementsByClassName('sidebar-container')[0]
      this.$_sidebarElm && this.$_sidebarElm.addEventListener('transitionend', this.$_sidebarResizeHandler)
    },
    resize() {
      this.$$chartInstance && this.$$chartInstance.resize()
    },
    destroyListener() {
      window.removeEventListener('resize', this.$_resizeHandler)
      this.$_resizeHandler = null
      this.$_sidebarElm && this.$_sidebarElm.removeEventListener('transitionend', this.$_sidebarResizeHandler)
    }
  },
  watch: {
    dataSource: function() {
      const type = this.type
      const option = chartOptions[`get${type}Option`](this.title, this.dataSource, type.toLowerCase())
      this.setOption(option)
    },
    theme: function() {
      this.$$chartInstance.dispose()
      this.initChart(this.id)
    }
  },
  computed: {
    theme() {
      return this.$store.state.settings.activeTheme
    }
  }
}
